<template>
  <view class="order-item">
    <view class="header" @click="navigateToDetails">
      <v-icon size="36rpx" src="@/static/icons/cart-merchant.svg" />
      <view class="merchant-name">
        <view class="name-text">
          {{ order.merchant_name }}
        </view>
      </view>
      <view class="status" :class="{ highlight: status === '待支付' }">
        {{ status }}
      </view>
    </view>
    <template
      v-for="(product, index) in order.order_detail_list"
      :key="product.sku_id"
    >
      <view v-if="index !== 0" class="divider" />
      <order-product
        :product="product"
        :show-buy-again="status === '已收货' || status === '已完成'"
        @click="navigateToDetails"
        @show-comment="$emit('show-comment', product)"
        @buy-again="$emit('buy-again', product)"
      />
    </template>
    <view class="summary" @click="navigateToDetails">
      <view class="summary-label">
        {{ summaryText }}
      </view>
      <v-price :price="order.payment" size="32rpx" color="#333333" />
    </view>
    <view v-if="hasAftersales || buttonList.length" class="footer">
      <view v-if="hasAftersales" class="aftersales-status">
        存在售后
      </view>
      <v-button
        v-if="buttonList.includes('取消订单')"
        :custom-style="{
          height: '78rpx',
          padding: '0 28rpx',
          minWidth: '168rpx'
        }"
        type="plain"
        @click="cancelOrder"
      >
        取消订单
      </v-button>
      <v-button
        v-if="buttonList.includes('去支付')"
        :custom-style="{
          height: '78rpx',
          padding: '0 28rpx',
          minWidth: '168rpx'
        }"
        type="primary"
        @click="payOrder"
      >
        去支付
      </v-button>
      <v-button
        v-if="buttonList.includes('删除订单')"
        :custom-style="{
          height: '78rpx',
          padding: '0 28rpx',
          minWidth: '168rpx'
        }"
        type="plain"
        @click="deleteOrder"
      >
        删除订单
      </v-button>
      <v-button
        v-if="buttonList.includes('确认收货')"
        :custom-style="{
          height: '78rpx',
          padding: '0 28rpx',
          minWidth: '168rpx'
        }"
        type="primary"
        @click="confirmOrder"
      >
        确认收货
      </v-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import OrderProduct from './order-product.vue';
import usePayment from '@/composables/use-payment';

const props = defineProps<{
  order: OrderVO;
}>();

const emits = defineEmits<{
  refresh: [];
  'show-comment': [product: OrderDetailVO];
  'buy-again': [product: OrderDetailVO];
}>();

const order = toRef(props, 'order');
const status = computed(() => {
  switch (true) {
    case order.value.status === 'PLACED_AN_ORDER':
      return '待支付';
    case order.value.status === 'CANCEL':
      return '订单已取消';
    case order.value.status === 'EXPIRED':
      return '订单已失效';
    case order.value.status === 'PAID':
      return '待发货';
    case order.value.status === 'SHIPPED':
      return '待收货';
    case order.value.status === 'SIGNED_FOR':
      return '已收货';
    case order.value.status === 'COMPLETED':
      return '已完成';
    case order.value.status === 'PART_REFUND':
      return '部分退款';
    case order.value.status === 'ALL_REFUND':
      return '已退款';
    default:
      return '';
  }
});
const hasAftersales = computed(() => {
  return (
    order.value.refund_status !== 'NONE' &&
    order.value.refund_status !== 'CLOSE'
  );
});
const buttonList = computed(() => {
  const list = [];
  if (status.value === '待支付') {
    list.push('取消订单');
    list.push('去支付');
  } else if (status.value === '订单已取消' || status.value === '订单已失效') {
    list.push('删除订单');
  } else if (status.value === '待收货') {
    list.push('确认收货');
  }
  return list;
});

const summaryText = computed(() => {
  switch (order.value.pay_status) {
    case 'UNPAID':
      return '应付';
    case 'PAID':
      return '已付';
    default:
      return '';
  }
});

const cancelOrder = async () => {
  const result = await uni.showModal({
    title: '提示',
    content: '确定取消订单吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.getOrderSubmitMergeNoCancel(order.value.merge_no);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '取消订单成功', icon: 'none' });
      emits('refresh');
      break;
  }
};
const payOrder = async () => {
  const { payOrder } = usePayment();
  let result = false;
  // #ifdef MP-ALIPAY
  if (order.value.pay_product === 'MERGE_PAY') {
    const tradeNo = order.value.out_merge_no ?? order.value.out_trade_no;
    result = await payOrder(tradeNo, { bizType: 'merge_order' });
  } else {
    result = await payOrder(order.value.out_trade_no);
  }
  // #endif
  // #ifdef MP-WEIXIN
  const response = await $api.getOrderRestateMergeNoPayment(
    order.value.merge_no
  );
  switch (response.__error) {
    case undefined:
      result = await payOrder({
        timeStamp: response.data.timeStamp,
        nonceStr: response.data.nonceStr,
        package: response.data.packageVal,
        signType: response.data.signType,
        paySign: response.data.paySign
      });
      break;
  }
  // #endif
  if (result) emits('refresh');
};
const deleteOrder = async () => {
  const result = await uni.showModal({
    title: '提示',
    content: '确定删除订单吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.deleteOrderQueryId(order.value.id);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '删除订单成功', icon: 'none' });
      emits('refresh');
      break;
  }
};
const confirmOrder = async () => {
  const result = await uni.showModal({
    title: '提示',
    content: '确定确认收货吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.getOrderSubmitIdConfirm(order.value.id);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '确认收货成功', icon: 'none' });
      emits('refresh');
      break;
  }
};

const navigateToDetails = () => {
  uni.navigateTo({ url: `/pages/order/order-details?id=${order.value.id}` });
};
</script>

<style lang="scss" scoped>
.order-item {
  padding: 28rpx 24rpx;
  margin: 0 24rpx 24rpx;
  background-color: white;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  gap: 28rpx;
  .header {
    height: 40rpx;
    display: flex;
    align-items: center;
    gap: 20rpx;
    .merchant-name {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      .name-text {
        font-size: 28rpx;
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
      }
    }
    .status {
      line-height: 36rpx;
      &.highlight {
        color: #ff2f3b;
      }
    }
  }
  .divider {
    height: 1px;
    background-color: #eeeeee;
  }
  .summary {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 8rpx;
    .summary-label {
      font-size: 28rpx;
    }
  }
  .footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 20rpx;
    .aftersales-status {
      margin-right: auto;
      color: #ff2f3b;
      padding: 12rpx 0;
    }
  }
}
</style>
